const {
    ipcRenderer,
    remote
} = window.top.require('electron');
const log = window.top.require('electron-log');
log.transports.file.level = 'info';
log.transports.console.level = true;
const dialog = remote.dialog;
const fs = window.top.require("fs");
const path = window.top.require("path");
const xml2js = window.top.require('xml2js');
const uuid = window.top.require('uuid');
const packageObj = window.top.require(path.join(`${window.top.__dirname}`, '..', '..', '..', 'package.json'));
const Q = window.top.require('q');

//加密
const crypto = window.top.require('crypto');
//定义jqeury
if (typeof module === 'object') {
    window.jQuery = window.$ = module.exports;
}



//xml2js默认会把子子节点的值变为一个数组, explicitArray设置为false
var xmlParser = new xml2js.Parser({
    explicitArray: false,
    mergeAttrs: false, //mergeAttrs为true时，会忽略所有属性节点不生成
    attrNameProcessors: [nameToUpperCase],
    tagNameProcessors: [nameToUpperCase],
    trim: true
})

//创建errCode对象
const errCodeObj = {
    50000: '数字签名(signature)不对或数字签名不存在',
    50001: '文件格式不对',
    50002: '文件超出了1GB',
    50003: '文件无法读取',
    50004: '业务请求不存在',
    70001: '单元识别代码不存在',
    70002: '单元识别代码层级数据出',
    70003: '单元识别代码层级数据出错',
    70004: '箱码重复',
    70005: '农药信息查询有误',
    70006: '农药产品过期',
    70007: '上传的农药信息与上传的追溯码不匹配',
    70008: '缺少文件签名'
};

//获取api接口数组
let api = fs.readFileSync(path.join(`${window.top.__dirname}`, '..', '..', '..', 'interface.ini.' + packageObj.interfaceConfig)).toString();
let apiArr = api.split(";");
apiArr.splice(apiArr.length - 1, 1);

//禁用网页缩放事件
document.onkeydown = function (e) {
    var ev = window.event || e;
    var code = ev.keyCode || ev.which;
    var condition_code = (code == 48 || code == 187 || code == 189);
    var condition_ctrl = (event.metaKey || event.ctrlKey);
    if (condition_code && condition_ctrl) {
        return false;
    }
}

/**
 * 获取公司信息
 * @param {*} callback 
 */
function getCompany(callback) {
    let company = ipcRenderer.sendSync('get-company-info', '');
    callback(company);
}

function nameToUpperCase(name) {
    return name.toUpperCase();
}

function isEmpty(a) {
    return a == undefined || a == null ||
        (is(a, 'String') && a == '') ||
        (is(a, 'Array') && a.length == 0);
}

function is(obj, type) {
    return (type === "Null" && obj === null) ||
        (type === "Undefined" && obj === void 0) ||
        (type === "Number" && isFinite(obj)) ||
        Object.prototype.toString.call(obj).slice(8, -1) === type;
}
/**
 * 表单查询输入框采集
 */
function formSearchCollection() {
    var q = [];
    $('#form1 input[ifield]').each(function () {
        if (!isEmpty($(this).val()))
            q.push({
                name: $(this).attr('id'),
                field: $(this).attr('ifield'),
                op: $(this).attr('ioperation'),
                type: $(this).attr('idatatype'),
                data: encodeURIComponent($(this).val()),
                ignorecase: $(this).attr('ignorecase')
            });
    });
    $('#form1 select[ifield]').each(function () {
        if (!isEmpty($(this).val()) && $(this).val() != "null")
            q.push({
                field: $(this).attr('ifield'),
                op: $(this).attr('ioperation'),
                type: $(this).attr('idatatype'),
                data: encodeURIComponent($(this).val())
            });
    });
    //增加排序字段
    $("#form1 input[name='q_sort_input_hid']").each(function () {
        if (!isEmpty($(this).val())) {
            var arr = $(this).val().split(",");
            for (var i = 0; i < arr.length; i++) {
                var vals = arr[i].split(":");
                q.push({
                    field: vals[0],
                    order: vals[1]
                });
            }
        }
    });
    return q;
}

/**
 * 将对象转换成字符串
 * @param obj
 * @returns
 */
function json2Str(obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        if (t == "string") obj = '"' + obj + '"';
        return String(obj);
    } else {
        // recurse array or object
        var n, v, json = [],
            arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n];
            t = typeof (v);
            if (t == "string") v = '"' + v + '"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
}
/**
 * 选择文件保存目录并下载
 * @param {} saveFolder 
 */
function choseDirectoryAndDownload(downloadPath) {
    dialog.showSaveDialog({
        //默认路径
        //defaultPath: '../Desktop',
        //选择操作，此处是打开文件夹
        properties: [
            'openDirectory',
        ],
        //过滤条件
        filters: [{
            name: 'xml',
            extensions: ['xml']
        }]
    }, function (savePath) {
        if (savePath) {
            ipcRenderer.send('download', downloadPath + "+" + savePath);
        }
    });
}

/**
 * 指定对象字段格式化
 * @param {} obj 
 * @param {*} arr 
 */
function filedFormat(obj, arr) {
    arr.map(function (item) {
        obj[item] = obj[item].replace(/-/g, '');
    });

}
/**
 * 生成xml文件并提交
 * @param {*} obj xml对象
 * @param {*} submitUrl 提交url
 * @param {*} xmlBuilder 
 * @param {*} rootName xml根节点名称
 * @param {*} index layer单窗index
 */
function xmlParserThenSubmit(obj, submitUrl, xmlBuilder, rootName, index, reportType) {
    let sXml = xmlBuilder.buildObject(obj);
    xmlParser.parseString(sXml, function (err, result) {
        if (err) {
            console.error(err);
            layer.close(index);
            layer.alert('xml文件内容生成失败！', {
                title: '提示'
            });
            return;
        }
        let sConvertXml = xmlBuilder.buildObject(result[rootName]);

        $('.tip-content').text('xml文件已生成完毕，正在提交往服务器！');
        // 创建一个hash对象
        const md5 = crypto.createHash('md5');
        //发送请求
        $.ajax({
            url: submitUrl,
            data: sConvertXml,
            dataType: 'xml',
            timeout: 60000,
            type: 'POST',
            beforeSend: function (xhr, settings) {
                xhr.setRequestHeader('signature', window.parent.companyinfo.signature);
                xhr.setRequestHeader('content_md5', md5.update(sConvertXml).digest('hex'));
                xhr.setRequestHeader('version', '1');
                $("#btnSubmits").addClass("layui-btn-disabled");
                $("#btnSubmits").attr("disabled", true);
            },
            success: function (data) {
                layer.close(index);
                let isSuccess = $(data).find('RESULT').attr('SUCCESS');
                let rqeId = $(data).find('RESULT').attr('REQID');
                //上报返回结构1，成功，0，失败
                if (isSuccess == 1) {
                    layer.alert('提交成功，请在首页【上报记录查询】中查看处理结果！', function (index) {
                        $(window.top.document).find('li.active .closer').click();
                    });
                    //根据上报类型解析上报条数
                    let reportCodeNum = null;
                    if (reportType == "case1_prdu") {
                        reportCodeNum = result[rootName].TRACECODES.TRACECODE.length || 1;
                    } else if (reportType == "case1_output") {
                        reportCodeNum = result[rootName].PACKCODES.PACKCODE.length || 1;
                    } else if (reportType == "case2_prdu") {
                        reportCodeNum = result[rootName].TRACECODES.TRACECODE.length || 1;
                    } else if (reportType == "case2_output") {
                        reportCodeNum = result[rootName].TRACECODES.TRACECODE.length || 1;
                    } else if (reportType == "case3_ALL") {
                        reportCodeNum = result[rootName].TRACECODES.TRACECODE.length || 1;
                    } else if (reportType == "recycle") {
                        reportCodeNum = result[rootName].TRACECODE.length || 1;
                    }
                    let file = `${window.top.__dirname}/../../../temp/` + uuid.v1() + '.xml';
                    //保存本地上报xml文件
                    file = file.replace(/\\/g, '/');
                    fs.writeFile(file, sConvertXml, 'utf8', error => {
                        if (error) {
                            log.error(error);
                            layer.close(index);
                            layer.alert('本地上报xml文件文件保存失败！', {
                                title: '提示'
                            });
                            return;
                        }
                        //将提交记录存储在本地
                        db.insertBysql("t_trace_upload_record", {
                            req_id: rqeId,
                            report_type: reportType,
                            report_time: new Date(),
                            report_code_num: reportCodeNum,
                            report_filepath: file,
                            process_status: 0,
                            enterprise_code: window.top.companyinfo.c_id,
                            enterprise_name: window.top.companyinfo.name
                        }, function (d) {

                        });
                    });
                } else {
                    let errorCode = $(data).find('RESULT').attr('ERRORCODE');
                    layer.alert(errCodeObj[errorCode], {
                        title: '提示'
                    });
                    resetBtnStatu();
                }
            },
            error: function (e) {
                log.error(e);
                layer.close(index);
                layer.alert('响应超时', {
                    title: '提示'
                });
                resetBtnStatu();
            }
        });
    });
}
/**
 * 显示追溯码错误行
 */
function showErrorNumber(errorArr) {
    $(".textarea-rows div").each(function () {
        if (errorArr.indexOf(parseInt($(this).text())) > -1) {
            $(this).css({
                "background-color": "red"
            });
        }
    })
}

//解除按钮禁用状态
function resetBtnStatu() {
    $("#btnSubmits").removeClass("layui-btn-disabled");
    $("#btnSubmits").attr("disabled", false);
}
/**
 * 返回一个Promise对象，使用then(fun1,fun2)方法，fun1执行success函数，
 * fun2执行error函数,一般使用catch()包括住异常错误
 * @param {*} obj ajax参数对象 
 */
function ajaxPromise(obj) {
    if (!obj.url) {
        throw new Error("obj参数的url必填！");
    }
    if (Object.prototype.toString.call(obj.beforeSend) == '[Object Function]') {
        throw new Error("obj参数的beforeSend函数必填");
    }
    let data1 = obj.data;
    const deferred = Q.defer();
    $.ajax({
        url: obj.url,
        type: obj.type || "get",
        timeout: obj.timeout || 0,
        data: data1 || "",
        dataType: obj.dataType || "text",
        beforeSend: obj.beforeSend,
        success: function (data) {
            deferred.resolve({
                data: data,
                obj: data1
            })
        },
        error: function (error) {
            deferred.reject({
                error: error,
                obj: data1
            })
        }
    });
    return deferred.promise;
};